<template>
  <div class="app-container">
    <el-row :gutter="20" class="mb8">
      <el-col :span="4" :xs="24">
        <SideBarThree :majorThree="gradeList" @selectNode="onTreeSelect" @addGrade="onAddGradeClick" @deleteGrade="onDeleteGradeClick" />
      </el-col>
      <el-col :span="20" :xs="24">
        <div class="table">
          <el-form class="search-container" :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="专业名称" prop="majorName">
              <el-input  v-model="queryParams.majorName" placeholder="请输入专业名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="全称" prop="gradeMajorName" >
              <el-input  v-model="queryParams.gradeMajorName" placeholder="请输入年级专业名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="是否分组" prop="groupFlag">
              <el-select v-model="queryParams.groupFlag" placeholder="请选择" filterable clearable style="width: 200px" >
                <el-option label="是" value="1" />
                <el-option label="否" value="0" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <div class="table-container">
            <el-row :gutter="10" class="mb8">
              <span>年级专业列表</span>
              <right-toolbar
                v-model:showSearch="showSearch"
                @queryTable="getList"
                add="system:major:add"
                @handleAdd="handleAdd"
                update="system:major:edit"
                @handleUpdate="handleUpdate"
                del="system:major:remove"
                @handleDelete="handleDelete"
                exp="system:major:export"
                @handleExport="handleExport"
                :single="single"
                :multiple="multiple"
              ></right-toolbar>
            </el-row>
            <el-table v-loading="loading" class="table-content" border :data="majorList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="所属学院" align="center" prop="deptName" />
              <el-table-column label="年级名称" align="center" prop="gradeName" />
              <el-table-column label="专业名称" align="center" prop="majorName" />
              <el-table-column label="全称" align="center" prop="gradeMajorName" />
              <el-table-column label="是否分组" align="center">
                <template #default="{ row }">
                  {{ String(row.groupFlag) === '1' ? '是' : '否' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template v-slot="{ row }">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['system:major:edit']">修改</el-button>
                  <el-button link type="danger" icon="Delete" @click="handleDelete(row)" v-hasPermi="['system:major:remove']">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination class="pagination-container" v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
  <index-dialog ref="dialogRef" @update="updateHandler"></index-dialog>
  <GradeDialog ref="gradeDialogRef" @update="onGradeUpdated" />
</template>

<script setup name="Major">
import { listMajor, getMajor, delMajor, addMajor, updateMajor } from '@/api/major'
import { getCurrentInstance, ref } from 'vue'
import indexDialog from './components/indexDialog.vue'
import SideBarThree from './components/sideBarThree.vue'
import { getGradeTree, addGrade, delGrade } from '@/api/grade'
import GradeDialog from './components/gradeDialog.vue'

const { proxy } = getCurrentInstance()

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  deptId: '',
  gradeId: ''
})
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const majorList = ref([])
const dialogRef = ref(null)
const queryRef = ref(null)
const gradeList = ref([])
const gradeDialogRef = ref(null)
const queryHandler = () => {
  queryParams.value.pageNum = 1
  getList()
}

const getList = () => {
  loading.value = true
  listMajor(queryParams.value).then(({ data }) => {
    majorList.value = data.rows
    total.value = data.total
    loading.value = false
  })
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.majorId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm('queryRef')
  queryHandler()
}
/** 修改按钮操作 */
const handleUpdate = (row) => {
  const majorId = row.majorId || ids.value
  dialogRef.value.openDialog(majorId)
}
/** 新增按钮操作 */
const handleAdd = () => {
  dialogRef.value.openDialog()
}
/** 删除按钮操作 */
const handleDelete = (row) => {
  const majorId = row.majorId || ids.value
  proxy.$modal
    .confirm('是否确认删除编号为"' + majorId + '"的数据项?')
    .then(function () {
      return delMajor(majorId)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
const updateHandler = () => {
  // 刷新表格
  queryHandler()
  // 刷新左侧树
  getGradeTreeList()
}
const handleExport = () => {
  proxy.download('system/major/export', { ...queryParams.value }, `major_${new Date().getTime()}.xlsx`)
}

//获取学院树
async function getGradeTreeList() {
  const response = await getGradeTree()
  gradeList.value = response.data.map((item) => {
    return {
      id: item.deptId,
      name: item.deptName,
      children: item.children.map((item) => {
        return {
          id: item.gradeId,
          name: item.gradeName,
          children: item.children.map((child) => {
            return {
              id: child.majorId,
              name: child.majorName
            }
          })
        }
      })
    }
  })
}
getList()
getGradeTreeList()

// 处理侧边树选择事件：点击学院查学院，点击年级查学院下的年级
function onTreeSelect(payload) {
  const { type, id, deptId } = payload
  if (type === 'dept') {
    queryParams.value.deptId = id
    queryParams.value.gradeId = ''
  } else if (type === 'grade') {
    queryParams.value.deptId = deptId || ''
    queryParams.value.gradeId = id
  } else if (type === 'major') {
    // 可选：选择专业时按照所属年级/学院筛选
    queryParams.value.deptId = payload.deptId || ''
    queryParams.value.gradeId = payload.gradeId || ''
  }
  queryParams.value.pageNum = 1
  getList()
}

// 侧边栏“添加年级”按钮：打开新增年级弹窗，预填当前学院ID（若有）
function onAddGradeClick(payload) {
  const preset = { deptId: payload?.deptId || '' }
  gradeDialogRef.value?.openDialog(null, preset)
}

// 年级新增/修改完成后刷新列表与树
function onGradeUpdated() {
  getList()
  getGradeTreeList()
}

function onDeleteGradeClick(payload) {
  const gradeId = payload?.gradeId
  const deptId = payload?.deptId
  if (!gradeId) {
    proxy.$modal.msgWarning('请先在树中选择一个年级')
    return
  }
  const deptNode = gradeList.value.find((d) => String(d.id) === String(deptId)) || gradeList.value.find((d) => (d.children || []).some((g) => String(g.id) === String(gradeId)))
  const gradeNode = deptNode?.children?.find((g) => String(g.id) === String(gradeId))
  const childMajors = gradeNode?.children || []

  if (childMajors.length > 0) {
    proxy.$modal.msgWarning(`该年级下存在专业，无法删除`)
    return
  }

  proxy.$modal
    .confirm('是否确认删除编号为"' + gradeId + '"的年级?')
    .then(function () {
      return delGrade(gradeId)
    })
    .then(() => {
      if (String(queryParams.value.gradeId) === String(gradeId)) {
        queryParams.value.gradeId = ''
      }
      getList()
      getGradeTreeList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
</script>
